package com.cn.common.utils.http;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class HttpRequestUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
    protected static CloseableHttpClient httpClient;
    private static final int timeout = 15000;

    public HttpRequestUtil() {
    }

    public static String get(String url) throws Exception {
        return get(url, (Map)null);
    }

    public static String get(String url, Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        String result = "";

        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000).setConnectionRequestTimeout(15000).setSocketTimeout(15000).build();
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            if (null != headers && headers.size() >= 1 && headers != null && !headers.isEmpty()) {
                headers.forEach((key, value) -> {
                    httpGet.addHeader(key, value);
                });
            }

            response = httpClient.execute(httpGet);
            HttpEntity entity = null;
            if (response != null) {
                entity = response.getEntity();
            }

            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException var14) {
            logger.error("http get request is error", var14);
            throw new Exception(var14.getMessage());
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException var13) {
                throw new Exception(var13.getMessage());
            }

        }

        return result;
    }

    public static String post(String url, String jsonString) throws Exception {
        return post(url, (String)jsonString, (Map)(new HashMap()));
    }

    public static String post(String url, String jsonString, Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000).setConnectionRequestTimeout(15000).setSocketTimeout(15000).build();
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            if (null != headers && headers.size() >= 1 && headers != null && !headers.isEmpty()) {
                headers.forEach((key, value) -> {
                    httpPost.addHeader(key, value);
                });
            }

            response = httpClient.execute(httpPost);
            HttpEntity entity = null;
            if (response != null) {
                entity = response.getEntity();
            }

            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException var16) {
            logger.error("http get request is error", var16);
            throw new Exception(var16.getMessage());
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException var15) {
                logger.error(var15.getMessage());
                throw new Exception(var15.getMessage());
            }

        }

        return result;
    }

    public static String post(String url, String jsonString, Integer _timeout) throws Exception {
        int postTimeout = 15000;
        if (null != _timeout) {
            postTimeout = _timeout;
        }

        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(postTimeout).setConnectionRequestTimeout(postTimeout).setSocketTimeout(postTimeout).build();
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            HttpEntity entity = null;
            if (response != null) {
                entity = response.getEntity();
            }

            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (IOException var17) {
            logger.error("http get request is error", var17);
            throw new Exception(var17.getMessage());
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException var16) {
                logger.error(var16.getMessage());
                throw new Exception(var16.getMessage());
            }

        }

        return result;
    }

    public static String post(String url, Map<String, String> param) throws Exception {
        return post(url, (Map)param, (Map)null);
    }

    public static String post(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        String result = "";
        Object entity = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000).setConnectionRequestTimeout(15000).setSocketTimeout(15000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Accept", "application/json");
            if (null != headers && headers.size() >= 1 && headers != null && !headers.isEmpty()) {
                headers.forEach((key, value) -> {
                    httpPost.addHeader(key, value);
                });
            }

            if (null != params && params.size() >= 1) {
                List<NameValuePair> paramList = new ArrayList();
                params.forEach((k, v) -> {
                    paramList.add(new BasicNameValuePair(k, v));
                });
                entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity((HttpEntity)entity);
            }

            response = httpClient.execute(httpPost);
            if (response != null) {
                entity = response.getEntity();
            }

            if (null != entity) {
                result = EntityUtils.toString((HttpEntity)entity, "UTF-8");
            }
        } catch (IOException var16) {
            logger.error("http get request is error", var16);
            throw new Exception(var16.getMessage());
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException var15) {
                logger.error("http get request is error", var15);
                throw new Exception(var15.getMessage());
            }

        }

        return result;
    }


    public static String get(String url, Map<String, String> paramMap, Cookie[] cookies) {
        StringBuilder cookieStr = new StringBuilder();
        Cookie[] var4 = cookies;
        int var5 = cookies.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            Cookie c = var4[var6];
            cookieStr.append(c.getName()).append("=").append(c.getValue()).append("; ");
        }

        return get(url, paramMap, cookieStr.toString());
    }

    public static String get(String url, Map<String, String> paramMap, String cookies) {
        StringBuilder paramStr = new StringBuilder("?");
        Iterator var4 = paramMap.entrySet().iterator();

        String result;
        while(var4.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var4.next();
            result = (String)entry.getKey();
            String value = (String)entry.getValue();
            paramStr.append(result).append("=").append(value).append("&");
        }

        url = url + paramStr;
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000).setConnectionRequestTimeout(15000).setSocketTimeout(15000).build();
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-type", "application/json; charset=utf-8");
        httpGet.setHeader("Accept", "application/json");
        httpGet.addHeader("Cookie", cookies.toString());
        result = "";

        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            Throwable var8 = null;

            try {
                HttpEntity entity = null;
                if (response != null) {
                    entity = response.getEntity();
                }

                if (null != entity) {
                    result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                }
            } catch (Throwable var18) {
                var8 = var18;
                throw var18;
            } finally {
                if (response != null) {
                    if (var8 != null) {
                        try {
                            response.close();
                        } catch (Throwable var17) {
                            var8.addSuppressed(var17);
                        }
                    } else {
                        response.close();
                    }
                }

            }

            return result;
        } catch (IOException var20) {
            throw new RuntimeException(var20.getMessage(), var20);
        }
    }


    public static void out(HttpServletResponse response, Object data) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;

        try {
            out = response.getWriter();
            out.append(JSON.toJSONString(data));
            out.flush();
        } catch (IOException var7) {
            logger.error(var7.getMessage());
        } finally {
            if (null != out) {
                out.close();
            }

        }

    }

    public static Map<String, String> getParams(HttpServletRequest request) {
        Map<String, String> params = new TreeMap();
        Enumeration a = request.getParameterNames();

        while(a.hasMoreElements()) {
            String key = (String)a.nextElement();
            String val = request.getParameter(key);
            params.put(key, val);
        }
        return params;
    }

}